<?php
/**
 * @author Thibaut Cromphaut, Gaïtano Boeraeve, Mathias Helin, Dimitry Dierickx
 * @copyright  Copyright (c) 2011 Artevelde University College Ghent 
 *
 * NOT CURRENTLY IN USE
 */

class MessageController extends Zend_Controller_Action
{

    private $_redirector = null;

    public function init()
    {
        $this->_redirector = $this->_helper->getHelper('Redirector');
        $this->stylesBase = $this->view->baseUrl() . '/styles/';
    }

    public function preDispatch()
    {
        // Set the stylesheet for this view -- custom one
        $this->view->headLink()->appendStylesheet($this->stylesBase.'pm.css');
        
        // Only allow these types of actions for a logged in user
        if ( Zend_Auth::getInstance()->hasIdentity() )
        {
            switch ( $this->getRequest()->getActionName() )
            {
                case 'index':
                    break;
                default:
                    $this->_helper->redirector('index', 'index');
                    break;
            }
        }
        else
        {
            // Uitloggen kan niet als je niet ingelogd bent.
            switch ( $this->getRequest()->getActionName() ) {
                case 'logout':
                    $this->_helper->redirector('index');
                    break;
                default:
                    break;
            }
        } 
    }

    public function indexAction()
    {
        $this->_helper->redirector('index', 'admin');
        /*
        // Set our view
        $view = $this->_getView('Messages');
        // Get the logged in User-object
        $user   = Zend_Auth::getInstance()->getStorage()->read();
        // Set our partial vars
        $vars           = array(
            'user'      => $user,
            'messages'  => $this->_getAllMessagesForCurrentUser(),
            'unread'    => $this->_getNumberOfUnreadMessagesForUser($user->Id),
        );
        // Set our content
        $view->user     = $user;
        $view->content  = $view->partial('partials/block-user-messages.phtml', $vars);
        */
    }

    public function viewAction()
    {
        // Render the main message layout
        $this->_helper->viewRenderer('message/index', null, true);//render('index');
        // Set our view
        $view = $this->view;
        // Get the logged in User-object
        $user   = Zend_Auth::getInstance()->getStorage()->read();
        // Get the parent id
        $parent_id  = $this->_getParam('id');
        // Get the form
        $replyform  = $this->replyMessage();
        // Get all messages for this PM
        $messages   = $this->_getAllMessagesByParentId($parent_id);
        // Get this message's user IDs
        $userIDs[]  = $messages[0]->Userfrom->Id;
        $userIDs[]  = $messages[0]->UserTo->Id;
        // We can only view this PM if we are either part of the conversation
        if(in_array($user->Id, $userIDs))
        {
            // Set our partial vars
            $vars           = array(
                'user'      => $user,
                'parent_id' => $parent_id,
                'messages'  => $messages,
                'form_add'  => $replyform,
                'unread'    => $this->_getNumberOfUnreadMessagesForUser($user->Id),
            );
            // Set our content
            $view->user     = ($messages[0]->Userfrom->Id == $user->Id ? $messages[0]->Userto : $messages[0]->Userfrom);
            $view->content  = $view->partial('message/view.phtml', $vars);
            // Mark this message as read
            $this->markAsRead($parent_id, $user->Id);
        }
        else
            $this->_helper->redirector('index', 'message');
    }

    public function replyMessage()
    {
        // Render the main message layout
        $this->_helper->viewRenderer('message/index', null, true);//render('index');
        // Set our view
        $view = $this->view;
        // Get the logged in User-object
        $user   = Zend_Auth::getInstance()->getStorage()->read();
        // Next, we will need some request parameters
        $pm_to      = (string)$this->getRequest()->getParam('to');
        $pm_id      = (string)$this->getRequest()->getParam('id');
        // Set up the form
        $form = $this->_getReplyMessageForm($pm_id);
        
        if ($this->getRequest()->isPost()) 
	{
            // Get the form data
            $formData  = $this->_request->getPost();
            $form->users_user_to->addValidators(array(
                array('Regex', false, array('/^[^'.$user->Id.']$/'))
            ))->addErrorMessage('You cannot send a message to yourself.');
            // Validate form
            if ($form->isValid($formData)) 
            {
                // Save message
                if(($message_id = $this->saveForm($form)) != null)
                {
                    // Reset form
                    $form->populate(
                        array(
                            'message_content' => $pm_subject,
                        )
                    );
                }
            }
        }
        else
        {
            // We shall require some variables
            $pm_subject = "";
            // If we have a reply Id, we need to do a little bit of extra work
            if($pm_id != null)
            {
                // Get parent message
                $parent_message = $this->_getMessage($pm_id);
                
                // Now we need to set some variables
                $pm_subject = "RE: ".$parent_message->Subject;
                $pm_to  = ($user->Id == $parent_message->Userfrom->Id ? $parent_message->Userto->Id : $parent_message->Userfrom->Id);
            }

            $form->populate(
                array(
                    'parent_id' => $pm_id,
                    'users_user_to' => $pm_to,
                    'message_subject' => $pm_subject,
                )
            );
        }
        
        return $form;
    }
    
    public function addMessage()
    {
        // Render the main message layout
        $this->_helper->viewRenderer('message/index', null, true);
        // Set our view
        $view = $this->view;
        // Get the logged in User-object
        $user   = Zend_Auth::getInstance()->getStorage()->read();
        // Next, we will need some request parameters
        $pm_to      = (string)$this->getRequest()->getParam('to');
        // Set up the form
        $form = $this->_getAddMessageForm($pm_id);
        // Request action
        if ($this->getRequest()->isPost()) 
	{
            // Get the form data
            $formData  = $this->_request->getPost();
            // We should be sending ourself a message
            if($user->Id == $formData['user_to_id'])
            {
                $form->users_user_to->setError('You cannot message yourself.');
            }
            // Validate form
            if ($form->isValid($formData)) 
            {
                // Save message
                if(($message_id = $this->saveForm($form)) != null)
                {
                    // Reset form
                    $form->populate(
                        array(
                            'message_content' => $pm_subject,
                        )
                    );
                }
            }
        }
        else
        {
            // Push data into our form
            $form->populate(
                array(
                    'users_user_to' => $pm_to,
                )
            );
        }
        
        return $form;
    }
    
    public function saveForm($form)
    {
        // Get the values
        $values = $form->getValues();
        // Get the logged in User-object
        $user   = Zend_Auth::getInstance()->getStorage()->read();
        // Create our message
        $message = new Application_Model_Message();
        // Set only the interesting values
        if(strlen($values['parent_id']))
            $message->ParentId  = $values['parent_id'];
        $message->UserToId      = $values['users_user_to'];
        $message->UserFromId    = $user->Id;
        $message->Subject       = $values['message_subject'];
        $message->Content       = $values['message_content'];
        // Save the message
        $mapper     = new Application_Model_MessageMapper();                
        $message_id = $mapper->save($message);
        // Check if this message has a parent ID
        if($message_id != null && strlen($values['parent_id']))
        {
            $message_id = $values['parent_id'];
        }
        
        return $message_id;
    }

    public function deleteAction()
    {
        $id = (string)$this->getRequest()->getParam('id');
        $messageMapper = new Application_Model_MessageMapper();
        $messageMapper->delete($id, array($this->getCurrentUserID()));
        $this->_helper->redirector('index', 'message');
    }

    public function deletebyadminAction()
    {
        $id = (string)$this->getRequest()->getParam('id');
        $messageMapper = new Application_Model_MessageMapper();
        $messageMapper->deleteByAdmin($id);
        $this->_helper->redirector('index', 'message');
    }

    /**
     * @return string $user_id 
     *
     */
    public function getCurrentUserID()
    {
        // Get the storage object, return the ID
        $storage = Zend_Auth::getInstance()->getStorage()->read();
        return $storage->Id;
    }

    /**
     * @return string $user_role 
     *
     */
    public function getCurrentUserRole()
    {
        // Get the storage object, return the role
        $storage = Zend_Auth::getInstance()->getStorage()->read();
        return $storage->Role;
    }

    public function markAsRead($parent_id, $user_id)
    {
        $messageMapper = new Application_Model_MessageMapper();
        $messageMapper->markAsRead($parent_id, array($user_id));
    }

    /**
     * @return Array
     *
     */
    private function _getAllMessages()
    {
        $MessageMapper = new Application_Model_MessageMapper();
        $MessageArray = $MessageMapper->fetchAll();

        return $MessageArray;
    }

    /**
     * @return Array(Application_Model_Message)
     *
     */
    private function _getAllMessagesForCurrentUser()
    {
        return $this->_getAllMessagesForUser($this->getCurrentUserID());
    }

    /**
     * @return Array(Application_Model_Message)
     *
     */
    private function _getAllMessagesForUser($user_id)
    {
        $MessageMapper = new Application_Model_MessageMapper();
        $MessageArray = $MessageMapper->fetchByUserId($user_id);

        return $MessageArray;
    }

    /**
     * @return Array
     *
     */
    private function _getAllMessagesByParentId($parent_id)
    {
        $MessageMapper = new Application_Model_MessageMapper();
        $MessageArray = $MessageMapper->fetchByParentId($parent_id);

        return $MessageArray;
    }

    private function _getNumberOfUnreadMessagesForUser($user_id)
    {
        $MessageMapper = new Application_Model_MessageMapper();
        return $MessageMapper->fetchUnreadMessagesCountForUser($user_id);
    }

    /**
     * @return Application_Form_EditUser
     *
     */
    private function _getNewMessageForm()
    {
        return new Application_Form_NewMessage(array(
            'action' => $this->view->baseUrl() . '/message/new/',
            'post'   => 'post',
        ));
    }
    
    /**
     * @return Application_Form_EditUser
     *
     */
    private function _getReplyMessageForm($reply_id)
    {
        return new Application_Form_NewMessage(array(
            'action' => $this->view->baseUrl() . '/message/view/id/'.$reply_id,
            'post'   => 'post',
        ));
    }

    /**
     * @param string $id
     * @return Array
     *
     */
    private function _getMessage($id)
    {
        
        $MessageMapper = new Application_Model_MessageMapper();
        $messageArray = $MessageMapper->fetchById($id);

        return $messageArray;
    }

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    /**
     * Loops through a list of custom objects, passing each object to the partial.
     * The end result is a html-render of the all the partials.
     *
     * @param string $partial
     * @param Array $objects
     * @return string
     */
    private function _loopPartial($partial, $objects, $extravars=null)
    {
        $result = array();
        $count  = 0;
        if(count($objects))
        {
            foreach($objects as $object)
            {
                $count++;
                $vars       = array(
                    'object'    => $object,
                    'count'     => $count,
                );
                
                if(is_array($extravars))
                    $vars = array_merge($extravars, $vars);
                
                $result[]   = $this->_getView("")->partial('partials/'.$partial.'.phtml', $vars);
            }
        }
        
        return implode("\n", $result);
    }
    
    /**
     * Get the HTML pager for a list that requires pagination
     *
     * @param int $page_nr
     * @param int $total_pages
     * @param string $base_url
     * @param string $page_var
     * @return string 
     */
    private function _fetchPager($current_page, $total_pages, $base_url, $page_var)
    {
        $view   = $this->_getView("");
        $vars   = array(
            'cur_page'      => $current_page,
            'nr_of_pages'   => ceil($total_pages),
            'base_url'      => $base_url,
            'page_var'      => $page_var,
        );
        
        return $view->partial('partials/pager.phtml', $vars);
    }

    /**
     * This returns the view for this controller.
     *
     * @param string $title
     * @return Zend_View
     */
    private function _getView($title)
    {
        $view = $this->view;
        $view->title = $title;
        $view->headTitle($view->title, 'PREPEND');

        return $view;
    }
}